package com.app.net;

import com.app.commond.CmdHeartBeat;
import com.app.commond.sys.CmdBase;
import com.app.commond.sys.CmdFactoryCenter;
import com.app.protocol.ProtocolBasic;

import io.netty.channel.Channel;
import soft.common.tdPool.TdCachePoolExctor;
import soft.ifs.IByteBuff;
import soft.ifs.IWriteLog;
import soft.log.LogWriter;
import soft.net.model.CusNetSource;
import soft.net.model.NetEventListener;
import soft.net.protocol.IProtocol;

import java.util.HashMap;

public class MyNetEventListener extends NetEventListener {
	private static final IWriteLog log = new LogWriter(MyNetEventListener.class);
	TdCachePoolExctor tdExcutor;
	public static 	HashMap<Integer,CusNetSource> channelHashMap = new HashMap<>();

	public MyNetEventListener(Channel ch, TdCachePoolExctor tdExcutor) {
		super(ch);
		this.tdExcutor = tdExcutor;
	}

	@Override
	public IProtocol getProtocol() {
		return new ProtocolBasic();
	}

	@Override
	public void chanelConect() {

		try { // 连接时发送 心跳反馈
			CmdHeartBeat cmdheart = new CmdHeartBeat();
			cmdheart.setNetAndProtocol(channel, null);
			cmdheart.excute();
		} catch (Exception e) {
			log.error("连接建立时发送心跳回复失败", e);
		}

	}

	@Override
	public void dataReciveEvent(IByteBuff buff) {
		try {
			decoder.deCode(buff);
			if (decoder.hasDecDatas()) {
				IProtocol ndg = null;
				while ((ndg = decoder.popData()) != null) {
					ProtocolBasic myProtocol = (ProtocolBasic) ndg;
					log.info("recvied client cmdkey:{} cmd", myProtocol.getCmdKey());
					CmdBase cmd = CmdFactoryCenter.getCmd(myProtocol.getCmdKey());
					cmd.setNetAndProtocol(channel, myProtocol);
					channelHashMap.put(myProtocol.getLockDevID(),channel);
					if (cmd.isHearBeat()) {// 心跳数据，立即返回
						cmd.run();
						continue;
					}
					tdExcutor.execute(cmd);
				}
			}
		} catch (Exception e) {
			log.error("解析数据，获取命令时失败", e);
		}
	}

	@Override
	public void closeEvent() {
		// do nothing
	}

}
